"use client"

import { useEffect, useState } from "react"
import { ethers } from 'ethers'
import { BrowserProvider, parseUnits } from "ethers";

// Components
import Header from "./components/Header"
import List from "./components/List"
import Token from "./components/Token"
import Trade from "./components/Trade"

// ABIs & Config
import Factory from "./abis/Factory.json"
import config from "./config.json"
import images from "./images.json"

export default function Home() {

  const [provider, setProvider] = useState(null)
  const [account, setAccount] = useState(null)
  const [factory, setFactory] = useState(null)
  const [fee, setFee] = useState(0)
  const [showCreate, setShowCreate] = useState(false)
  const [showTrade, setShowTrade] = useState(false)
  const [tokens, setTokens] = useState([])
  const [token, setToken] = useState(null)

  const loadBlockchainData = async () => {
    let provider;
    if (window.ethereum == null) {
        console.log("MetaMask not installed; using read-only defaults")
        provider = ethers.getDefaultProvider()
        setProvider(provider)
    } else {
        provider = new ethers.BrowserProvider(window.ethereum)
        setProvider(provider) 
    }

    const network = await provider.getNetwork()
    console.log("network", network.chainId)
    const address = config[network.chainId].factory.address

    //获胜合约实例(合约地址，合约ABI，提供者)
    const factory = new ethers.Contract(
      config[network.chainId].factory.address,
      Factory,
      provider
    )
    setFactory(factory)
    setFee(await factory.fee())
    //fee 10000000000000000n

    const totalTokens = await factory.totalTokens()
    const tokens = [];
    // get the first 6 tokens listed
    for (let i = 0; i < totalTokens; i++) {
      if (i == 6) {
        break
      }
      const address = await factory.tokens(i)
      const tokenSale = await factory.tokenSales(address) 
      // We create our own object to store extra fields
      // like images
      const token = {
        token: tokenSale.token,
        name: tokenSale.name,
        creator: tokenSale.creator,
        sold: tokenSale.sold,
        raised: tokenSale.raised,
        isOpen: tokenSale.isOpen,
        image: images[i]
      }
      tokens.push(token)
    }

    // We reverse the array so we can get the most
    // recent token listed to display first
    setTokens(tokens.reverse())
  }

  useEffect(() => {
    loadBlockchainData()
  }, [])

  const toggleCreate = async () =>{
    setShowCreate(!showCreate)
  }

  function toggleTrade(token) {
    setToken(token)
    setShowTrade(!showTrade)
  }


  return (
    <div className="page">
      <Header account={account} setAccount={setAccount}/>
      <main>
        <div className="create">
            <button className="btn--fancy" onClick={factory && account && toggleCreate}>
            {
              !factory?("[ contract not deploy ]"):
              !account?("[ please connect wallet ]"):
              ("[ create token ]")
            }
          </button>
        </div>

        <div className="listings">
          <h1>Listings</h1>
          <div className="tokens">
            {!account ? (
              <p>please connect wallet</p>
            ) : tokens.length === 0 ? (
              <p>No tokens listed</p>
            ) : (
              tokens.map((token, index) => (
                <Token
                  toggleTrade={toggleTrade}
                  token={token}
                  key={index}
                />
              ))
            )}
          </div>
        </div>  
      </main>
      {showCreate && <List toggleCreate={toggleCreate} provider={provider} factory={factory} fee={fee} />}
      {showTrade && <Trade toggleTrade={toggleTrade} token={token} provider={provider} factory={factory} />}
    </div>
  );
}
